<script lang="ts">
/**
 * @author leo
 * @description #19507 图片主页视图
 */
import { Component, Vue, Prop, Mixins } from "vue-property-decorator";
import { EventBus, ContentModal } from "feok-lib";
import TableWithSumMix from "../../mixins/TableWithSumMix";

import ImagesAdminLayout from "@/layouts/ImagesAdminLayout.vue";
import TotalCard from "@/components/TotalCard";
import TitleCard from "@/components/TitleCard";
import PicCard from "@/components/PicCard";
import Viewer from "@/components/Viewer";
import PhotoUpload from "@/views/archives/photo/PhotoUpload.view.vue";
import GroupSelect from "@/components/GroupSelect";

import {
  getApiAssetsFile,
  putApiAssetsFile,
  getApiAssetsGroup,
  postApiAssetsGroup,
  putApiAssetsFileId,
  deleteApiAssetsFileId,
  putApiAssetsGroupId,
  deleteApiAssetsGroupId,
  getApiAssetsFileSummary,
  postApiAssetsUseStatistics
} from "@/model";

@Component({
  components: {
    ImagesAdminLayout,
    TotalCard,
    TitleCard,
    PicCard,
    ContentModal,
    Viewer,
    PhotoUpload,
    GroupSelect
  }
})
export default class ArchivesPhoto extends Mixins(TableWithSumMix) {
  get selectionArr() {
    return this.data.filter((res: any) => res.checked === true);
  }
  get imgUrlArr() {
    return this.data.map((res: any) => res.url);
  }

  public query = {
    name: "",
    type: "IMAGE"
  };

  // 当期活动的分组
  public activedGroup = {
    name: "",
    id: 1
  };

  // 统计对象
  public totalObj = {
    count: 0,
    handleSize: 0,
    useSize: 0
  };

  public menuArr: any[] = []; // 菜单数组
  public limit = 20;

  public modalValue: boolean = false;
  public modalTitle: any = {
    upload: "上传照片"
  };
  public modalType: string = "";

  public addGroupVisible = false; // 添加分组开关
  public addGroupName = ""; // 添加分组名称
  public isIndeterminate = false; // 半选中
  public checkAll = false; // 全选
  public pictureViewVistable = false;
  public changeFilesGroupVisible = false;
  public newFilesGroup: any = 0;

  public fetchDataAction = this.getApiAssetsFile;

  // 拉取资料列表
  public async getApiAssetsFile(query: any, page: number, limit: number) {
    try {
      const { data = [], total = 0 } = await getApiAssetsFile({
        ...query,
        groupId: this.activedGroup.id === 0 ? "" : this.activedGroup.id,
        pageNo: page,
        pageSize: limit
      });

      return {
        datas: data,
        total
      };
    } catch (err) {
      console.log(err);
    }
  }

  // 切换分类
  // item:分类对象
  public clickMenu(item: any) {
    try {
      this.activedGroup = JSON.parse(JSON.stringify(item));
      this.fetchData();
      this.clearSelection();
    } catch (e) {
      console.log(e);
    }
  }

  // 确定添加分组
  public async srueAddGroup() {
    try {
      await postApiAssetsGroup({
        name: this.addGroupName,
        type: "IMAGE" // 分类
      });
      EventBus.$emit("success", "操作成功");
      await this.fetchGroupList();
    } catch (error) {
      console.log(error);
    }
    this.addGroupVisible = false;
  }

  // 取消添加分组
  public closeAddGroupVisible() {
    this.addGroupName = "";
    this.addGroupVisible = false;
  }

  // 分组重命名
  public async onChangeGroupName(name: string) {
    try {
      await putApiAssetsGroupId({
        id: this.activedGroup.id,
        name,
        type: "IMAGE"
      });
      // EventBus.$emit('success', '操作成功');

      await this.fetchGroupList();
      this.activedGroup.name = name;
    } catch (error) {
      console.log(error);
    }
  }

  //  删除分组
  public async onClickDelGroup() {
    const done = await this.$del(
      `仅删除分组，不删除视频，组内视频将自动归入未分组`
    );
    try {
      await deleteApiAssetsGroupId({ id: this.activedGroup.id });

      EventBus.$emit("success", "操作成功");
      this.refresh();
    } catch (error) {
    } finally {
      done();
    }
  }

  // 批量操作文件
  public async doFiles(params: any) {
    try {
      await putApiAssetsFile(params);
      EventBus.$emit("success", "操作成功");

      this.handleSearchData();
    } catch (error) {
      console.log(error);
    }
  }

  // 展开批量修改文件分组弹窗
  public openChangeFilesVistable() {
    this.newFilesGroup = this.activedGroup.id;
  }

  // 批量修改文件分组
  public async changeFiles() {
    this.doFiles({
      ids: this.selectionArr.map((res: any) => res.id),
      groupId: this.newFilesGroup
    });
    this.changeFilesGroupVisible = false;
  }

  // 批量删除文件
  public async delFiles() {
    this.doFiles({
      ids: this.selectionArr.map((res: any) => res.id),
      deleted: "1"
    });
  }

  // 操作单个文件
  public async doFileById(params: any) {
    try {
      await putApiAssetsFileId(params);
      EventBus.$emit("success", "操作成功");
    } catch (error) {
      console.log(error);
    }
  }

  // 操作 - 改名
  public async changeFileName(id: number, name: string) {
    this.doFileById({ id, name });
    await this.fetchData();
  }

  // 操作 - 分组
  public async changeFileGroup(id: number, groupId: number) {
    this.doFileById({ id, groupId });
    this.handleSearchData();
  }

  // 操作 - 删除
  public async delFile(id: number) {
    this.doFileById({ id, deleted: "1" });
    this.handleSearchData();
  }

  // 操作 - 下载
  public async downloadImage(item: any) {
    this.postApiAssetsUseStatistics(item.id);

    const aElement = document.createElement("a");
    aElement.target = "_blank";
    aElement.href = item.url;
    document.body.appendChild(aElement);
    aElement.click();
    document.body.removeChild(aElement);
  }

  // 图片 - 全选
  public handleCheckAllChange(val: any) {
    this.data = this.data.map((res: any) => ({
      ...res,
      checked: val
    }));
    this.isIndeterminate = false;
  }

  // 图片 - 单条选中
  public handleCheckedChange(value: any, id: number) {
    const arrAllLength = this.data.length;
    this.data = this.data.map((res: any) => ({
      ...res,
      checked: res.id === id ? value : res.checked
    }));

    const checkedCount = this.selectionArr.length;
    this.checkAll = arrAllLength === checkedCount;
    this.isIndeterminate = checkedCount > 0 && checkedCount < arrAllLength;
  }

  // 计算点击数
  public async postApiAssetsUseStatistics(fileId: number) {
    try {
      await postApiAssetsUseStatistics({
        fileId,
        type: "DOWNLOAD" // DOWNLOAD/PLAY
      });
      this.getApiAssetsFileSummary();
    } catch (error) {
      console.log(error);
    }
  }

  // 图片 - 查看
  public handleClickPhoto(id: number) {
    this.postApiAssetsUseStatistics(id);

    let index2: number = 0;
    this.data.forEach((res: any, index: number) => {
      if (res.id === id) {
        index2 = index;
      }
    });

    this.pictureViewVistable = true;

    this.$nextTick(() => {
      const dom = this.$refs.ViewerWrap as any;
      if (dom) {
        dom.showImage(index2);
      }
    });
  }

  public openModal(type: string) {
    this.modalType = type;
    this.modalValue = true;
  }

  public onModalCancel() {
    this.modalValue = false;
  }

  public onModalDone() {
    this.onModalCancel();
    this.handleSearchData();
  }

  public async handleSearchData() {
    await this.fetchGroupList();
    if (this.menuArr.length) {
      await this.fetchData();
      this.clearSelection();
    }
  }

  public clearSelection() {
    this.isIndeterminate = false;
    this.checkAll = false;
  }

  // 拉取分组列表
  public async fetchGroupList() {
    try {
      this.menuArr = await getApiAssetsGroup({
        type: "IMAGE"
      });
    } catch (e) {
      console.log(e);
    }
  }

  public async refresh() {
    await this.fetchGroupList();
    if (this.menuArr.length) {
      this.activedGroup = this.menuArr[0];
      await this.fetchData();
      this.getApiAssetsFileSummary();
      this.clearSelection();
    }
  }

  // 拉去统计
  public async getApiAssetsFileSummary() {
    const result = await getApiAssetsFileSummary({ type: "IMAGE" });
    this.totalObj = result;
  }

  public async mounted() {
    this.refresh();
  }
}
</script>

<template>
  <div class="images_admin_view">
    <!-- 统计模块 -->
    <TotalCard
      :num="totalObj.count"
      :flow="totalObj.handleSize"
      :storage="(totalObj.useSize/1024/1024/1024).toFixed(4)"
    ></TotalCard>

    <!-- 标题场景 -->
    <div slot="breadcrumb" class="images_admin_view-upload_wrap">
      <el-form
        ref="form"
        :model="query"
        :inline="true"
        size="mini"
        class="patch-el-form-search-wrap"
        @submit.native.prevent
        label-width="0px"
      >
        <el-form-item>
          <el-input
            v-model="query.name"
            clearable
            @keyup.enter.native="handleSearch"
            placeholder="图片名称"
          ></el-input>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleSearch">搜索</el-button>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="openModal('upload')">点击上传</el-button>

          <el-popover
            placement="bottom"
            width="325"
            trigger="click"
            v-model="changeFilesGroupVisible"
            @show="openChangeFilesVistable"
          >
            <template v-if="changeFilesGroupVisible">
              <p>选择分组</p>
              <GroupSelect v-model="newFilesGroup" :query="{type: 'IMAGE'}" style="margin:6px 0;"></GroupSelect>
              <div style="text-align: right; margin: 0">
                <el-button size="mini" @click="changeFilesGroupVisible = false">取消</el-button>
                <el-button type="primary" size="mini" @click="changeFiles">确定</el-button>
              </div>
            </template>
            <el-button
              slot="reference"
              style="margin-left:10px;"
              v-show="selectionArr && selectionArr.length>0"
            >修改分组</el-button>
          </el-popover>
          <el-button
            style="margin-left:10px;"
            v-show="selectionArr && selectionArr.length>0"
            @click="delFiles"
          >删除</el-button>
        </el-form-item>
      </el-form>
    </div>

    <ImagesAdminLayout>
      <!-- 左侧菜单 -->
      <div slot="menu" class="images_admin_view-menu_wrap">
        <ul class="images_admin_view-menu">
          <li
            v-for="(item,index) in menuArr"
            :key="index"
            class="images_admin_view-menu_li"
            :class="{'images_admin_view-menu_li-actived':activedGroup.id === item.id}"
            @click="clickMenu(item)"
          >
            <span class="feok-fr">{{item.acount}}</span>
            {{item.name}}
          </li>
        </ul>
        <el-popover placement="right" width="325" trigger="click" v-model="addGroupVisible">
          <p>添加分组</p>
          <el-input v-model="addGroupName" placeholder="请输入内容" style="margin:8px 0;"></el-input>
          <div style="text-align: right; margin: 0">
            <el-button size="mini" type="text" @click="addGroupVisible = false">取消</el-button>
            <el-button type="primary" size="mini" @click="srueAddGroup">确定</el-button>
          </div>
          <el-button slot="reference" size="mini" plain class="images_admin_view-menu_new">
            <i class="iconfont icon-jia"></i> 新建分组
          </el-button>
        </el-popover>
      </div>

      <!-- 右侧内容 -->
      <div slot="content" class="images_admin_view-content_wrap">
        <!-- 分类操作 -->
        <TitleCard
          :name="activedGroup.name"
          :group-id="activedGroup.id"
          @on-change-group-name="onChangeGroupName"
          @on-click-del-group="onClickDelGroup"
        ></TitleCard>

        <el-checkbox
          style="padding: 10px;"
          :indeterminate="isIndeterminate"
          v-model="checkAll "
          @change="handleCheckAllChange"
        >全选</el-checkbox>

        <div class="images_admin_view-content_border">
          <PicCard
            class="images_admin_view-content_list"
            v-for="(item,index) in data"
            :key="item.name"
            :path="item.url"
            :name="item.name"
            :id="item.id"
            :team-id="activedGroup.id"
            :checked="item.checked"
            @on-change-name="changeFileName"
            @on-team="changeFileGroup"
            @on-delete="delFile"
            @on-change-checkbox="handleCheckedChange"
            @on-download="()=>downloadImage(item)"
            @on-big-pic="handleClickPhoto"
          ></PicCard>
        </div>
        <div>
          <el-pagination
            class="feok-fr"
            background
            @current-change="currentChange"
            :current-page.sync="page"
            :page-size="limit"
            layout="prev, pager, next, jumper"
            :total="total"
          ></el-pagination>
        </div>
      </div>
    </ImagesAdminLayout>

    <!--模态框详情页 start-->
    <ContentModal v-model="modalValue" :title="modalTitle[modalType]" @on-cancel="onModalCancel">
      <PhotoUpload v-if="modalType !== 'PHOTO'" @on-cancel="onModalCancel" @on-done="onModalDone"></PhotoUpload>
    </ContentModal>

    <!-- 图片浏览插件 -->
    <Viewer
      ref="ViewerWrap"
      v-if="pictureViewVistable"
      style="margin-left:20px;"
      :pic-list="imgUrlArr"
    />
  </div>
</template>

<style lang="less">
.images_admin_view {
  background: #fff;
  padding: 10px;
  min-height: 100%;
  display: flex;
  flex-direction: column;
}
.images_admin_view-upload_wrap {
  margin-bottom: 10px;
  .icon-daochu {
    vertical-align: text-bottom;
  }
}
.images_admin_view-menu_wrap {
  width: 90%;
  margin: 0 auto;
}
.images_admin_view-search {
  width: 100%;
  margin: 10px 0;
}
.images_admin_view-lately {
  color: #7b898f;
  line-height: 32px;
  font-size: 14px;
  cursor: pointer;
  padding: 0 8px;
  margin-bottom: 10px;
  i {
    margin-right: 8px;
  }
  &:hover {
    background: #fff;
    border-radius: 4px;
  }
}
.images_admin_view-menu {
  padding: 6px 0;
}
.images_admin_view-menu_li {
  color: #7b898f;
  position: relative;
  list-style-type: none;
  line-height: 24px;
  font-size: 14px;
  padding: 0 8px;
  margin: 8px 0;
  cursor: pointer;
  &:hover {
    .images_admin_view-menu_li-actived;
  }
}
.images_admin_view-menu_li-actived {
  &::before {
    content: "";
    position: absolute;
    left: -5%;
    top: 0;
    width: 4px;
    height: 24px;
    background: #409eff;
  }
  color: #2d8cf0;
  font-weight: bold;
}
.images_admin_view-menu_new {
  display: block;
  margin: 10px auto;
  .icon-jia {
    vertical-align: text-bottom;
  }
}

.images_admin_view-content_wrap {
  display: flex;
  flex: 1;
  flex-direction: column;
  padding: 0 0 10px 10px;
}
.images_admin_view-content_border {
  flex: 1;
  border-top: 1px solid #f5f6f7;
  overflow-x: hidden;
}
.images_admin_view-img {
  background: blue;
  width: 150px;
  height: 200px;
  float: left;
  margin: 10px 10px 0px 0;
}
.images_admin_view-content_list {
  float: left;
  margin: 10px 10px 0;
}
</style>